﻿using System;


public class Node<T>//泛型节点类，T 表示可以存储任何类型的数据
{
    public Node<T> Next { get; set; }
    public T Data { get; set; }
    public Node(T t)
    {
        Next = null;
        Data = t;
    }
}

public class GenericList<T>
{
    private Node<T> head;
    private Node<T> tail;

    public GenericList()
    {
        tail = head = null;
    }
    public Node<T> Head
    {
        get => head;
    }
    public void Add(T t)//向链表尾部添加新元素
    {
        Node<T> n = new Node<T>(t);
        if (tail == null) head = tail = n;
        else
        {
            tail.Next = n;
            tail = n;
        }
    }
    // 添加的ForEach方法
    public void ForEach(Action<T> action)
    {
        for (Node<T> node = head; node != null; node = node.Next)
        {
            action(node.Data);
        }
    }
}
class Program
{
static void Main(string[] args)
{
        // 整型list
        GenericList<int> intlist = new GenericList<int>();
        for (int x = 0; x < 10; x++)
        {
            intlist.Add(x);
        }

        Console.WriteLine("打印链表元素:");
        intlist.ForEach(x => Console.WriteLine(x));

        // 求最大值
        int max = int.MinValue;
        intlist.ForEach(x => { if (x > max) max = x; });
        Console.WriteLine($"最大值: {max}");

        // 求最小值
        int min = int.MaxValue;
        intlist.ForEach(x => { if (x < min) min = x; });
        Console.WriteLine($"最小值: {min}");

        // 求和
        int sum = 0;
        intlist.ForEach(x => sum += x);
        Console.WriteLine($"和: {sum}");

        // 字符串型list
        GenericList<string> strList = new GenericList<string>();
        for (int x = 0; x < 10; x++)
        {
            strList.Add("str" + x);
        }

        Console.WriteLine("\n打印字符串链表:");
        strList.ForEach(s => Console.WriteLine(s));
    }
}


